<template>
	<Content title="现场仓调拨">
		<view class="from-box">
			<view class="content" style="position: relative; top: 0; left: 0; height: 60rpx">
				<u-icon @click.native="scanCode()" name="scan" size="24"
					style="position: absolute; top: 6rpx; right: 10rpx"></u-icon>
			</view>
			<view class="content">
				<view>出库仓库：</view>
				<u-form labelPosition="left" :model="searchParams" labelWidth="80" labelAlign="left" :rules="rules"
					ref="uForm">
					<u-form-item label="仓库位置" required prop="team">
						<MySelect cascader :isFullValue='true' v-model="searchParams.outWarehouseLocation"
							:option="outWarehouseLocationList" @change="outWarehouseLocationListChange"
							placeholder="请选择"></MySelect>
					</u-form-item>
					<u-form-item label="仓库名称" required prop="team">
						<uni-data-select v-model="searchParams.outBackupConfig" :localdata="outBackupConfigList"
							placeholder="请选择"></uni-data-select>
						<!--<u-input label-->
						<!--v-model="searchParams.outBackupConfig"-->
						<!--placeholder="请填写仓库名称"></u-input>-->
					</u-form-item>
					<u-form-item label="物料编号" required prop="team">
						<u-input label v-model="searchParams.materielCode" placeholder="请填写物料编号"></u-input>
					</u-form-item>
				</u-form>
				<view>
					<u-button class="btn" type="primary" @click="pageChange()" text="查询"></u-button>
				</view>
			</view>
			<view class="content">
				<scroll-view :scroll-y="true" style="max-height: 600rpx" class="scrollView"
					@scrolltolower="bottomOut()">
					<view v-for="(item, index) in dataArr" :key="index">
						<view>
							<view class="check" @click="checkboxChange(item)" :class="[item.checked ? 'checked' : '']">
								<view v-if="item.checked">√</view>
							</view>
						</view>
						<u-form labelPosition="left" :model="item" labelWidth="80" labelAlign="left" :rules="rules"
							ref="uForm">
							<u-form-item label="物料编号" required prop="team">
								<u-input label readonly v-model="item.materialCode" placeholder="请填写物料编号"></u-input>
							</u-form-item>
							<u-form-item label="物料名称" prop="team">
								<u-input label readonly v-model="item.materialName" placeholder="请填写物料名称"></u-input>
							</u-form-item>
							<u-form-item label="数量" required prop="team">
								<u-input label type="number" v-model="item.inventoryQuantity"
									:disabled="item.inventoryQuantityDisabled" @change="inventoryQuantityChange"
									placeholder="请填写数量"></u-input>
							</u-form-item>
							<u-form-item label="批次号" prop="team">
								<u-input label readonly v-model="item.batchNumber" placeholder="请填写批次号"></u-input>
							</u-form-item>
							<u-form-item label="图号规格" prop="team">
								<u-input label readonly v-model="item.customMaterialCode"
									placeholder="请填写图号规格"></u-input>
							</u-form-item>
							<u-form-item label="材料牌号" prop="team">
								<u-input label readonly v-model="item.materialMark" placeholder="请填写材料牌号"></u-input>
							</u-form-item>
						</u-form>
					</view>
				</scroll-view>
			</view>
			<view class="content" style="margin-bottom: 160rpx">
				<view>入库仓库：</view>
				<u-form labelPosition="left" :model="searchParams" labelWidth="80" :isFullValue='true' labelAlign="left"
					:rules="rules" ref="uForm">
					<u-form-item label="仓库位置" required prop="team">
						<MySelect cascader v-model="searchParams.enterWarehouseLocation"
							:option="enterWarehouseLocationList" @change="enterWarehouseLocationListChange"
							placeholder="请选择"></MySelect>
					</u-form-item>
					<u-form-item label="仓库名称" required prop="team">
						<uni-data-select v-model="searchParams.enterBackupConfig" :localdata="enterBackupConfigList"
							placeholder="请选择"></uni-data-select>
					</u-form-item>
				</u-form>
				<view class="btn-v">
					<view class="but-box">
						<u-button class="btn" @click="onBack" text="取消"></u-button>
						<u-button class="btn" type="primary" @click="onConfirm" :loading="loading" :disabled="loading"
							:text="`确定(${checkDataInventoryQuantity})`"></u-button>
					</view>
				</view>
			</view>

			<u-toast ref="uToast"></u-toast>
		</view>
	</Content>
</template>

<script>
	import Content from "@/components/content/index.vue";
	import MySelect from "@/components/mySelect.vue";
	import fetch from "@/utils/fetch";
	import wmsFetch from "@/utils/wmsFetch";
	import recursion from "@/utils/recursion";
	import {
		getDictData
	} from "@/api/index.js";
	import {
		findOrgByToken
	} from "@/api/moldManagement/transferRecord.js";
	import {
		initScan,
		startScan,
		stopScan
	} from "@/utils/scan";
	import {
		getUserInfo
	} from "@/store/user";

	export default {
		components: {
			Content,
			MySelect
		},
		data() {
			return {
				searchParams: {},
				outWarehouseLocationList: [],
				warehouseLocation: "",
				outBackupConfigList: [],
				rules: {},
				dataArr: [],
				status: "loadmore", //初始加载状态
				pageNum: 1, //默认页数
				pageSize: 1, //一页加载数据条数
				pages: 2,
				checkDataArr: [],
				enterWarehouseLocationList: [],
				enterBackupConfigList: [],
				scanCodeInventoryQuantity: null,
				scanCodeBatchNumber: null,
				scanCodeResidueNumber: null,
				scanCodeLabelInfoList: [],
				scanList: [],

				checkDataInventoryQuantity: 0,

				loading: false,
			};
		},
		onShow: function() {
			// #ifdef APP-PLUS
			initScan(this.scanSuccess);
			startScan();
			// #endif
			this.getOutWarehouseLocationList();
		},
		onHide() {
			// #ifdef APP-PLUS
			stopScan();
			// #endif
		},
		methods: {
			inventoryQuantityChange() {
				this.checkDataInventoryQuantity = 0;
				console.log('inventoryQuantityChange')
				const add = function(a, b) {
					let c, d, e;
					try {
						c = a.toString().split(".")[1].length;
					} catch (f) {
						c = 0;
					}
					try {
						d = b.toString().split(".")[1].length;
					} catch (f) {
						d = 0;
					}
					return e = Math.pow(10, Math.max(c, d)), (mul(a, e) + mul(b, e)) / e;
				}
				const mul = function(a, b) {
					var c = 0,
						d = a.toString(),
						e = b.toString();
					try {
						c += d.split(".")[1].length;
					} catch (f) {}
					try {
						c += e.split(".")[1].length;
					} catch (f) {}
					return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
				}
				let sum = 0;
				for (let i = 0; i < this.checkDataArr.length; i++) {
					sum = add(sum, this.checkDataArr[i].inventoryQuantity);
				}
				this.$set(this, 'checkDataInventoryQuantity', sum)
			},
			// 红外线扫码成功后
			async scanSuccess(code) {
				const res = {
					result: code,
				};
				// 下面就是写取到结果后的事情
				this.afterScan(res);
			},
			getOutWarehouseLocationList() {
				let params = {
					level: 0,
					status: '1'
				};
				findOrgByToken(params).then(({
					data
				}) => {
					const obj = {
						label: "name",
						text: "name",
						value: "code",
						children: "children",
					};
					this.outWarehouseLocationList = recursion.convertTree(data, obj);
					this.enterWarehouseLocationList = recursion.convertTree(data, obj);
				});
			},
			outWarehouseLocationListChange(val, names) {
				if (!this.searchParams.outWarehouseLocation) {
					this.searchParams = {};
					this.warehouseLocation = "";
					this.outBackupConfigList = [];
					this.dataArr = [];
					this.status = "loadmore"; //初始加载状态
					this.pageNum = 1; //默认页数
					this.pageSize = 1; //一页加载数据条数
					this.pages = 2;
					this.checkDataArr = [];
					this.enterBackupConfigList = [];
					this.scanCodeInventoryQuantity = null;
					this.scanCodeResidueNumber = null;
					this.scanCodeBatchNumber = null;
					this.scanCodeLabelInfoList = [];
					this.checkDataInventoryQuantity = 0;
					this.scanList = [];
					this.loading = false;
				}
				this.warehouseLocation = names;
				this.searchParams.outBackupConfig = "";
				this.changeOutWarehouseLocation(this.searchParams.outWarehouseLocation);
			},
			enterWarehouseLocationListChange(val, names) {
				if (!this.searchParams.enterWarehouseLocation) {
					this.searchParams = {};
					this.warehouseLocation = "";
					this.outBackupConfigList = [];
					this.dataArr = [];
					this.status = "loadmore"; //初始加载状态
					this.pageNum = 1; //默认页数
					this.pageSize = 1; //一页加载数据条数
					this.pages = 2;
					this.checkDataArr = [];
					this.enterBackupConfigList = [];
					this.scanCodeInventoryQuantity = null;
					this.scanCodeResidueNumber = null;
					this.scanCodeBatchNumber = null;
					this.scanCodeLabelInfoList = [];
					this.checkDataInventoryQuantity = 0;
					this.scanList = [];
					this.loading = false;
				}
				this.searchParams.enterWarehouseLocationName = names;
				this.searchParams.enterBackupConfig = "";
				this.changeEnterWarehouseLocation(
					this.searchParams.enterWarehouseLocation
				);
			},
			changeOutWarehouseLocation(val) {
				fetch("post", "/dms/dmsBackupConfig/queryPage", {
					pageNum: 1,
					pageSize: 9999,
					functionLocation: [val[val.length - 1]],
					status: "1",
					onSiteWarehouse: '是'
				}).then((res) => {
					this.outBackupConfigList = res.data.records.map((item) => {
						return {
							text: item.backupName,
							value: item.backupNo,
						};
					});
				});
			},
			changeEnterWarehouseLocation(val) {
				fetch("post", "/dms/dmsBackupConfig/queryPage", {
					pageNum: 1,
					pageSize: 9999,
					status: "1",
					functionLocation: [val[val.length - 1]],
				}).then((res) => {
					this.enterBackupConfigList = res.data.records.map((item) => {
						return {
							text: item.backupName,
							value: item.backupNo,
							onSiteWarehouse: item.onSiteWarehouse,
							id: item.id
						};
					});
				});
			},
			pageChange() {
				this.pageNum = 1;
				this.pages = 2;
				this.dataArr = [];
				this.checkDataArr = [];
				this.scanCodeInventoryQuantity = null;
				this.scanCodeResidueNumber = null;
				this.scanCodeBatchNumber = null;
				this.scanCodeLabelInfoList = [];
				this.scanList = [];
				this.searchList();
			},
			searchList() {
				if (!this.searchParams.outWarehouseLocation) {
					uni.$emit("openToast", {
						title: "请选择出库仓库位置",
					});
					return false;
				}
				if (!this.searchParams.outBackupConfig) {
					uni.$emit("openToast", {
						title: "请输入出库仓库名称",
					});
					return false;
				}
				// if (!this.searchParams.materielCode) {
				//   uni.$emit("openToast", {
				//     title: "请输入出库仓库物料编号",
				//   });
				//   return false;
				// }

				let params = {
					materialCode: this.searchParams.materielCode ?
						this.searchParams.materielCode : "",
					pageNum: this.pageNum,
					pageSize: this.pageSize,
				};
				if (
					this.searchParams.outWarehouseLocation &&
					this.searchParams.outWarehouseLocation.length > 0
				) {
					params["outWarehouseLocation"] =
						this.searchParams.outWarehouseLocation[0];
				}
				if (this.scanCodeBatchNumber) {
					params["batchNumber"] = this.scanCodeBatchNumber;
				}

				if (this.searchParams.outBackupConfig) {
					for (let i = 0; i < this.outBackupConfigList.length; i++) {
						if (
							this.outBackupConfigList[i].value ===
							this.searchParams.outBackupConfig
						) {
							params["warehouseName"] = this.outBackupConfigList[i].text;
						}
					}
				}

				fetch(
					"post",
					"/dms/warehouseDetails/getWarehouseDetailsList",
					params
				).then((res) => {
					this.status = "loadmore";
					this.pages = res.data.pages;
					const dataClone = res.data.records;
					if (this.pageNum === 1) {

						this.dataArr = dataClone;
					}

					if (this.pageNum > 1) {
						this.dataArr = this.dataArr.concat(dataClone);
					}
					if (
						(this.pageNum >= 1 && dataClone.length < 1) ||
						dataClone.length === 0
					) {
						this.status = "nomore";
						return;
					}
				});
			},
			//触底加载数据
			bottomOut() {
				this.status = "loading"; //滑到底部的时候显示状态为加载中
				this.pageNum += 1; //请求页数+1
				//判断没数据后停止请求接口数据，并修改显示状态为没有更多
				if (this.pageNum > this.pages) {
					this.status = "nomore";
					return;
				}
				this.searchList(); //调用数据请求
			},
			checkboxChange(val) {
				let isShow = false;
				for (let i = 0; i < this.checkDataArr.length; i++) {
					if (this.checkDataArr[i].id === val.id) {
						this.checkDataArr.splice(i, 1);
						isShow = true;
						break;
					}
				}
				for (let i = 0; i < this.dataArr.length; i++) {
					if (this.dataArr[i].id === val.id) {
						this.dataArr[i].checked = !this.dataArr[i].checked;
					}
				}
				this.dataArr.splice(0, 0);
				if (!isShow) {
					this.checkDataArr.push(val);
				}

				this.inventoryQuantityChange()
			},
			onBack() {
				uni.navigateBack({
					delta: 1,
				});
			},
			onConfirm() {
				if (!this.searchParams.outWarehouseLocation) {
					uni.$emit("openToast", {
						title: "请选择出库仓库位置",
					});
					return false;
				}
				if (!this.searchParams.outBackupConfig) {
					uni.$emit("openToast", {
						title: "请输入出库仓库名称",
					});
					return false;
				}
				// if (!this.searchParams.materielCode) {
				//   uni.$emit("openToast", {
				//     title: "请输入出库仓库物料编号",
				//   });
				//   return false;
				// }

				if (this.checkDataArr.length === 0) {
					uni.$emit("openToast", {
						title: "至少选择一条物料",
					});
					return false;
				}
				if (!this.searchParams.enterWarehouseLocation) {
					uni.$emit("openToast", {
						title: "请选择入库仓库位置",
					});
					return false;
				}
				if (!this.searchParams.enterBackupConfig) {
					uni.$emit("openToast", {
						title: "请输入入库仓库名称",
					});
					return false;
				}


				this.loading = true;

				let data = [];
				let enterBackupConfig = "";
				let onSiteWarehouse = "";
				for (let i = 0; i < this.enterBackupConfigList.length; i++) {
					if (
						this.enterBackupConfigList[i].value ===
						this.searchParams.enterBackupConfig
					) {
						enterBackupConfig = this.enterBackupConfigList[i].text;
						onSiteWarehouse = this.enterBackupConfigList[i].onSiteWarehouse;
					}
				}

				let warehouseId = null;
				let outNumberIsZero = false;
				// let warn
				for (let i = 0; i < this.enterBackupConfigList.length; i++) {
					if (this.enterBackupConfigList[i].value === this.searchParams.enterBackupConfig) {
						warehouseId = this.enterBackupConfigList[i].id;
					}
				}

				for (let i = 0; i < this.checkDataArr.length; i++) {
					const elementData = this.checkDataArr[i];
					if (Number(elementData.inventoryQuantity) <= 0) {
						outNumberIsZero = true;
					}
					let obj = {
						outWarehouseLocationCode: this.searchParams.outWarehouseLocation[1],
						outBackupConfigCode: this.searchParams.outBackupConfig,
						warehouseLocationCode: this.searchParams.enterWarehouseLocation[1],
						warehouseId: warehouseId,
						warehouseLocationCodeList: this.searchParams.enterWarehouseLocation,
						outWarehouseLocation: this.warehouseLocation.join("/"),
						outBackupConfig: elementData.warehouseName,
						materielCode: elementData.materialCode,
						materielName: elementData.materialName,
						materielModel: elementData.materialModel ?
							elementData.materialModel : "",
						outNumber: elementData.inventoryQuantity ?
							Number(elementData.inventoryQuantity) : 0,
						batchNumber: elementData.batchNumber,
						enterWarehouseLocation: this.searchParams.enterWarehouseLocationName.join("/"),
						enterBackupConfig: enterBackupConfig,
						onSiteWarehouse: onSiteWarehouse,
						enterBackupConfigCode: this.searchParams.enterBackupConfig,
						materialMark: elementData.materialMark ?
							elementData.materialMark : "",
						customMaterialCode: elementData.customMaterialCode ?
							elementData.customMaterialCode : "",
						operator: getUserInfo().realname,
						labelInfoList: elementData.labelInfoList ? [{
							batchNo: elementData.labelInfoList[0].batchNo ? elementData.labelInfoList[0]
								.batchNo : "",
							labelQty: elementData.inventoryQuantity ? Number(elementData.inventoryQuantity) :
								0,
							produceDate: elementData.labelInfoList[0].produceDate ? elementData.labelInfoList[
								0].produceDate : null,
							serialNo: elementData.labelInfoList[0].serialNo ? elementData.labelInfoList[0]
								.serialNo : ""
						}] : []
					};
					data.push(obj);
				}
				console.log(JSON.stringify(data))
				if (outNumberIsZero) {
					uni.$emit("openToast", {
						title: "输入的数量必须大于0",
					});
					this.loading = false;
					return;
				}
				fetch("post", "/dms/warehouseAllocation/add ", data)
					.then((res) => {
						this.loading = false;
						if (res.code === 200) {
							uni.$emit("openToast", {
								title: "操作成功",
							});
							this.searchParams = {};
							this.warehouseLocation = "";
							this.outBackupConfigList = [];
							this.dataArr = [];
							this.status = "loadmore"; //初始加载状态
							this.pageNum = 1; //默认页数
							this.pageSize = 1; //一页加载数据条数
							this.pages = 2;
							this.checkDataArr = [];
							this.enterBackupConfigList = [];
							this.scanCodeInventoryQuantity = null;
							this.scanCodeResidueNumber = null;
							this.scanCodeBatchNumber = null;
							this.scanCodeLabelInfoList = [];
							this.checkDataInventoryQuantity = 0;
							this.scanList = [];

						} else {
							uni.$emit("openToast", {
								title: res.mes,
							});
						}
					})
					.catch((error) => {
						this.loading = false;
					});
			},
			afterScan(res) {
				const that = this;
				const info = res.result.split(";") || [];
				if (info[0] === "scene_01") {
					let isShow = false;
					for (let i = 0; i < that.scanList.length; i++) {
						if (info[1] === that.scanList[i]) {
							isShow = true;
							return false;
						}
					}
					if (!isShow) {
						that.scanList.push(info[1]);
					}

					fetch("get", "/dms/labelPrinting/getLabelInfoBySerial", {
						tagSerial: info[1],
					}).then((res) => {
						if (res && res.code === 200) {
							that.searchParams.materielCode = res.data.materialCode ?
								res.data.materialCode :
								"";
							that.scanCodeInventoryQuantity = res.data.packingQuantity ?
								res.data.packingQuantity :
								"";
							that.scanCodeBatchNumber = res.data.batchNumber ?
								res.data.batchNumber :
								"";
							that.scanCodeResidueNumber = res.data.residueNumber ?
								res.data.residueNumber :
								"";
							that.scanCodeLabelInfoList = [{
								batchNo: res.data.batchNumber ? res.data.batchNumber : "",
								labelQty: res.data.labelQty ? res.data.labelQty : 0,
								produceDate: res.data.productionDate ? res.data.productionDate : "",
								serialNo: info[0] + ';' + info[1],
							}, ];
							that.scanCodeGetList();
						}
					});
				} else {
					let isShow = false;
					for (let i = 0; i < that.scanList.length; i++) {
						if (info[1] === that.scanList[i]) {
							isShow = true;
							return false;
						}
					}
					if (!isShow) {
						that.scanList.push(info[1]);
					}
					wmsFetch("post", "/warehouseService/getStockOutLabel", null, {
						corpId: "hx",
						data: {
							serialNo: info[0],
						},
					}).then((res) => {
						if (res && res.length !== 0) {
							const info = res.data[0]
							that.searchParams.materielCode = info.materialCode;
							that.scanCodeInventoryQuantity = info.labelQty;
							that.scanCodeBatchNumber = info.batchNo;
							that.scanCodeLabelInfoList = [{
								batchNo: info.batchNo ? info.batchNo : "",
								labelQty: info.labelQty ? info.labelQty : 0,
								produceDate: info.produceDate ? info.produceDate : "",
								serialNo: info.serialNo ? info.serialNo : "",
							}, ];
							that.scanCodeGetList();
						}
					});
				}
			},
			scanCode() {
				if (!this.searchParams.outWarehouseLocation) {
					uni.$emit("openToast", {
						title: "请选择出库仓库位置",
					});
					return false;
				}
				if (!this.searchParams.outBackupConfig) {
					uni.$emit("openToast", {
						title: "请输入出库仓库名称",
					});
					return false;
				}
				// 允许从相机和相册扫码
				const that = this;
				uni.scanCode({
					success: function(res) {
						that.afterScan(res);
					},
				});
			},
			scanCodeGetList() {
				const that = this;
				if (!this.searchParams.outWarehouseLocation) {
					uni.$emit("openToast", {
						title: "请选择出库仓库位置",
					});
					return false;
				}
				if (!this.searchParams.outBackupConfig) {
					uni.$emit("openToast", {
						title: "请输入出库仓库名称",
					});
					return false;
				}

				let params = {
					materialCode: this.searchParams.materielCode ?
						this.searchParams.materielCode : "",
					pageNum: 1,
					pageSize: 1,
				};
				if (
					this.searchParams.outWarehouseLocation &&
					this.searchParams.outWarehouseLocation.length > 0
				) {
					params["outWarehouseLocation"] =
						this.searchParams.outWarehouseLocation[0];
				}
				if (this.scanCodeBatchNumber) {
					params["batchNumber"] = this.scanCodeBatchNumber;
				}

				if (this.searchParams.outBackupConfig) {
					for (let i = 0; i < this.outBackupConfigList.length; i++) {
						if (
							this.outBackupConfigList[i].value ===
							this.searchParams.outBackupConfig
						) {
							params["warehouseName"] = this.outBackupConfigList[i].text;
						}
					}
				}

				fetch(
					"post",
					"/dms/warehouseDetails/getWarehouseDetailsList",
					params
				).then((res) => {
					this.status = "loadmore";
					this.pages = res.data.pages;
					const dataClone = res.data.records.map(item => {
						return {
							...item,
							code: that.scanList[that.scanList.length - 1],
						}
					})
					this.dataArr = this.dataArr.concat(dataClone);
					if (this.scanCodeInventoryQuantity) {
						for (let i = 0; i < this.dataArr.length; i++) {
							if (
								this.dataArr[i].materialCode === this.searchParams.materielCode &&
								this.dataArr[i].batchNumber === this.scanCodeBatchNumber &&
								this.dataArr[i].code === this.scanList[this.scanList.length - 1]
							) {
								this.dataArr[i].inventoryQuantity =
									this.scanCodeResidueNumber;
								this.dataArr[i].labelInfoList = this.scanCodeLabelInfoList;
								this.dataArr[i].checked = true;
								this.dataArr[i].inventoryQuantityDisabled = true;
								this.checkDataArr.push(this.dataArr[i]);

								this.inventoryQuantityChange()
							}
						}
					}
				});
			},
		},
	};
</script>

<style scoped lang="scss">
	.from-box {
		padding: 20rpx;
		height: 100%;
		overflow: auto;

		.content {
			padding: 20rpx 30rpx;
			background-color: #ffffff;
			border-radius: 5px;
			box-shadow: 0 12rpx 18rpx -6rpx rgba(0, 0, 0, 0.2);
			margin-bottom: 20rpx;
		}

		.check {
			display: inline-block;
			width: 50rpx;
			height: 50rpx;
			text-align: center;
			line-height: 50rpx;
			border: 1px solid #C8C9CC;

			&.checked {
				background-color: #2979FF;
				border: 1px solid #2979FF;
				color: #fff;
			}
		}
	}
</style>